<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class MainController extends Controller
{
	/**
	 *	搜索页面展示
	*/
   public function getSearch(Request $request){
   		if(!$request -> has('keyword')){
   			return back();
   		}
   	
   		// 根据关键字查询数据库
   		$goods = DB::table('goods_basis')
   				-> where('goodsname','like','%'.trim($request -> input('keyword')).'%')
   				-> orderBy($request -> input('active','evaulate'),'desc')
   				-> paginate(20);
   		
        return view('home.main.search',['goods' => $goods,'request' => $request -> all()]);
   }
   /**
	*	搜索下拉里出现的关键字信息
   */
	public function getAssist(){
		// 十条搜索下拉框里的商品信息
		$res = DB::table('goods_basis')
			-> where('status',0)
			-> orderBy('sales','desc')
			-> limit(10)
			-> get();
		return $res;
	}
	/**
	*	对数据库进行默认地址的更新
	*/
	public function getEditdefault($id){
		// 将所有状态进行还原
		$res = DB::table('sites')
				-> where('username',session('homeusername'))
				-> where('default',1)
				-> update(['default' => 0]);
		// 对当前选中的进行默认
		$res = DB::table('sites')
				-> where('id',$id)
				-> update(['default' => 1]);
	}
	/**
	*	对数据库地址进行更新
	*/
	public function getUpdateall(Request $request){
		$data['name'] = $request -> input('rename');
		$data['phone'] = $request -> input('rephone');
		$data['sites'] = $request -> input('detailsites');

		$res = DB::table('sites')
			-> where('id',$request -> input('id'))
			-> update($data);
		return $res;
	}
	/**
	*	添加新地址
	*/
	public function getInsert(Request $request){
		// 设置收获地址最大数的限制
		$count = DB::table('sites')
				-> where('username',session('homeusername'))
				-> count();
		if($count >= 5){
			return;
		}
		// 将所有状态进行还原
		$res1 = DB::table('sites')
				-> where('username',session('homeusername'))
				-> where('default',1)
				-> update(['default' => 0]);
		// 准备新添加的数据
		$data['name'] = $request -> input('rename');
		$data['phone'] = $request -> input('rephone');
		$data['sites'] = $request -> input('detailsites');
		$data['username'] = session('homeusername');
		$data['default'] = 1;
		$res = DB::table('sites')
			-> insertGetId($data);
		return $res;
	}
	/**
	*	支付流程检测 
	*	订单视图
	*/
	public function getPay(Request $request){
		if(empty(session('homeusername'))){
			session(['alert' => '123']);
			return back();
		}
		// 将收货地址拿出来
		$sites = DB::table('sites')
				-> where('username',session('homeusername'))
				-> orderBy('id','desc')
				-> limit(5)
				-> get();
		// 取出全部商品信息
		$allgoods = DB::table('goods_basis')
					-> where('status',0)
					-> get();
		
		// 判断数据来源是立即购买 or 购物车 测试中=====〉
		if($request -> has('count') && $request -> has('gid')){
			// 两个参数都有 -〉来自立即购买 
			foreach ($allgoods as $key => $value) {
			 	if($value['id'] == $request -> input('gid')){
			 		
			 		$create[] = array_merge($value,['count' => $request -> input('count'),'gid' => $request -> input('gid')]);
			 	}
			 } 
		}else{
			// 对来自购物车的数据进行处理
			// 取出帐号的id
			$uid = DB::table('user')
				-> where('username',session('homeusername'))
				-> value('id');

			// 根据取出来自购物车的数据
			$cart = DB::table('shopCart')
				-> where('uid',$uid)
				-> where(function($cart1){
					$cart1 -> where('status',1)
					-> get();
				})
				-> get();

			// 合并购物车数据和商品的数据
			$create = [];
		
			foreach ($allgoods as $key => $value) {
				foreach ($cart as $key => $value1) {
					if($value['id'] == $value1['gid']){
						$create[] = array_merge($value,$value1);
					}
				}
			}
		}

		// 要返回的数据
	
		return view('home.main.reorder',[
			'sites' => $sites,
			'create' => $create
			]);
	}
	/**
	*	详情页session的注销
	*/
	public function getForget(){
		if(session() -> has('alert')){
			session() -> forget('alert');
		}
	}
	/**
	*	订单生成视图
	*/
	public function getOrder(Request $request){
		// 将传过来的count进行切割
		$count = explode('N',$request -> input('content'));
		array_shift($count);
		foreach ($count as $key => $value) {
			$res[] = explode('L', $value);
		}
		// 取出相关商品的信息用到的数组
		foreach ($res as $key => $value) {
			$goodid[] = $value[0];
		}

		// 将商品的全部信息查出
		$goods = DB::table('goods_basis')
				-> where('status',0)
				-> whereIn('id',$goodid)
				-> get();
		// 将数量合入数组

		foreach ($goods as $key => $value) {
			foreach ($res as $key => $value1) {
				if($value['id'] == $value1[0]){
					$goods1[] = array_merge($value,['count'=>$value1[1]]);
				}
			}
		}

		// 把收获地址返回
		$sites = DB::table('sites')
			-> where('username',session('homeusername'))
			-> where(function($s){
				$s -> where('default',1)
					-> first();
			})
			-> first();
	
		// 把接收到的数组进行分割
		return view('home.main.uporder',[
			'sum' => $request -> input('sum'),
			'goods' => $goods1,
			'sites' => $sites
			]);
	}
	/**
	*	订单生成执行
	*/	
	public function postMainpay(Request $request){
		//判断用户帐号的金额是否满足该订单
		$affirm = DB::table('vault')
			-> join('user','vault.uid','=','user.id')
			-> where('user.username',session('homeusername'))
			-> select('vault.money','user.id')
			-> get()[0];

		if(empty($affirm) || $affirm['money'] < $request -> input('sum')){
			return 0;//余额不足请充值
		}
	
		// 对数据切割
		$first = explode('N', $request -> input('content'));
		array_shift($first);
		foreach ($first as $key => $value) {
			$second[] = explode('L', $value);
		}
		// 获取要查的商品的id
		foreach ($second as $key => $value) {
			$goodsid[] = $value[0];
		}
		// 拿到订单的地址
		$sites = DB::table('sites')
			-> where('username',session('homeusername'))
			-> where(function($s){
				$s -> where('default',1)
					-> first(); 
			})
			-> first();

		// 查出所有商品信息
		$goods = DB::table('goods_basis')
			-> where('status',0)
			-> whereIn('id',$goodsid)
			-> get();
		// 给所有商品拼接数量数组
		foreach ($goods as $key => $value) {
			foreach ($second as $key => $value1) {
				if($value['id'] == $value1[0]){
					$res[] = array_merge($value,['count' => $value1[1]]);
				}
			}
		}
		// 查询出商家的用户名
		foreach ($res as $key => $value) {
			$username[] = $value['username'];
		}
		// 查出卖家用户信息
		$user = DB::table('user')
			-> whereIn('username',$username)
			-> select('id','username')
			-> get();

		// 对要插入的数组进行拼接合并
		foreach ($res as $key => $value) {
			foreach ($user as $key => $value1) {
				if($value['username'] == $value1['username']){
					$order[] = [
					'subuser' => session('homeusername'),
					'subid' => $affirm['id'],
					'merchant' => $value1['username'],
					'merid' => $value1['id'],
					'goodsname' => $value['goodsname'],
					'gid' => $value['id'],
					'price' => ($value['price']*$value['count']),
					'ctime' => time(),
					'errctime' => time(),
					'merstatus' => 2,
					'site' => $sites['sites'],
					'sitename' => $sites['name'],
					'sitephone' => $sites['phone'],
					'num' => $value['count']
					]; 
				}
			}
		}
		// 订单表执行插入 订单日至表需要id 
		foreach ($order as $key => $value) {
			$ord_log_id[] = DB::table('my_order') -> insertGetId($value);
		}
		// 将订单提交的消息发送给卖家
		// 准备插入的数据
		foreach ($order as $key => $value) {
			$message[] = [
						'fuid' => $value['subid'],
						'fusername' => session('homeusername'),
						'fumerchant' => 0,
						'suid' => $value['merid'],
						'susername' => $value['merchant'],
						'sumerchant' => 1,
						'content' => session('homeusername').'在您的店里购买了'.$value['goodsname'].'请尽快发货',
						'time' => time()
						];
		}
		// 把消息插入表
		DB::table('message') -> insert($message);
		// 获得刚插入的id 将订单复制到订单日志
		$order_log = DB::table('my_order')
					-> whereIn('id',$ord_log_id)
					-> select('id as pid','subuser as customer','subid as customerid','merchant as seller','merid as sellerid','ctime as time','merstatus as status')
					-> get();
		
		// 插入订单日志的数据
		$ord_log_res = DB::table('my_order_log') -> insert($order_log);
		// 对购物车进行删除
		DB::table('shopCart')
		-> where('uid',$affirm['id'])
		-> where('status',1)
		-> delete();
		// 对用户的金额进行操作
		DB::beginTransaction();
		// 将买家的钱扣除
		$deduct = DB::table('vault')
				-> where('uid',$affirm['id'])
				-> update(['money'=> DB::table('vault') -> where('uid',$affirm['id']) -> value('money') - $request -> input('sum')]);
		// 将钱分给卖家
		foreach ($order as $key => $value) {
			$payee[] = DB::table('vault') 
						-> where('uid',$value['merid'])
						-> update(['money' => DB::table('vault') -> where('uid',$value['merid']) -> value('money') + $value['price']]);
		}
		if(!$deduct || in_array(0, $payee)){
			DB::rollBack();
			return 2;
		}else{
			DB::commit();
			return 1;
		}


	}
	public function getOrdersuccess(){
		return view('home.main.ordersuccess');
	}
	/**
	*	订单提交页金额充值的方法
	*/
	public function getAddmoney(Request $request){
		DB::beginTransaction();
		$res = DB::table('vault')
			-> where('uid',DB::table('user') -> where('username',session('homeusername')) -> value('id'))
			-> update(['money' => DB::table('vault') -> where('uid',DB::table('user') -> where('username',session('homeusername')) -> value('id')) -> value('money') + $request -> input('money')]);
		if($res){
			DB::commit();
			return 1;
		}else{
			DB::rollBack();
			return 0;
		}
	}
	/**
	*	详情页加入购物车
	*/
	public function getAddcart(Request $request){
		if(!session() -> has('homeusername')){
			return 2;
		}

		// 准备要插入的数据
		$data['uid'] = DB::table('user') -> where('username',session('homeusername')) -> value('id');
		$data['gid'] = $request -> input('gid');

		// 根据uid和gid判断此商品是否存在于此人购物车中 存在则不允许重复添加
		$cart = DB::table('shopCart')
					-> where('uid',$data['uid'])
					-> where('gid',$data['gid'])
					-> first();
		if(!empty($cart)){
			return 3;
		}
		$data['count'] = $request -> input('count');
		$data['ctime'] = time();
		// 对购物车进行插入
		$res = DB::table('shopCart')
				-> insert($data);
		if($res){
			return 1;
		}else{
			return 0;
		}
	}
	/**
	*	商品详情页ajax的回复插入
	*/
	public function getToes(Request $request){
		// 获取数据对回复表进行插入
		$data['pid'] = $request -> input('pid');
		$data['content'] = $request -> input('content');
		$data['ctime'] = time();
		$data['writer'] = session('homeusername');
		$data['uid'] = DB::table('user') -> where('username',session('homeusername')) -> value('id');
		$res = DB::table('to_evaluate')
			-> insert($data);
		if($res){
			// 对消息表进行插入
			$message['fuid'] = $data['uid'];
			$message['fusername'] = session('homeusername');
			$message['fumerchant'] = 0;
			// 获取收件人id和收件人姓名
			$user = DB::table('evaluate') -> where('id',$data['pid']) -> first();

			$message['suid'] = $user['uid'];
			$message['susername'] = $user['writer'];
			$message['sumerchant'] = 0;
			$message['content'] = $message['fusername'].'回复了您的评论 =〉'.$data['content'];
			$message['time'] = time();
			// 对消息表进行插入
			DB::table('message')
				-> insert($message);

			return $data['writer'];
		}else{
			return 0;
		}
	}
	/**
	*	消息的提示
	*/
	public function getHintmessage(){
		if(session() -> has('homeusername')){
			$hint = DB::table('message')
				-> where('susername',session('homeusername'))
				-> where('read',0)
				-> count();
			return $hint;
		}

		return 0;
	}
	/**
	*	网站配置信息
	*/
	public function getConfig(Request $request){
		$res = DB::table('configuration')
			-> first();
		return $res;
	}
}
